package com.yingxin.yxerp.module.dingtalk.util;

import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.dingtalk.constant.WeComUrlConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 获取access_token工具类
 */

@Slf4j
@Service
public class WeComAccessTokenUtil {

    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 获取 accessToken
     */
    public String getAccessToken(String corpid, String corpsecret) {
        ResponseEntity<Map> response = restTemplate.getForEntity(
                WeComUrlConstant.GET_ACCESS_TOKEN_URL+"?corpid="+corpid+"&corpsecret="+corpsecret, Map.class );
        Map data = response.getBody();
        Integer errcode = (Integer) data.get("errcode");
        if( errcode != 0 ){
            throw new BizException("获取企微access_token失败，企微反馈："+data.get("errmsg"));
        }
        return (String) data.get("access_token");
    }

}
